<script setup>
/**
 * & 文件引入区域
 */
import { ref, onMounted, nextTick, reactive } from "vue";
import { useUseStore } from "@/stores/user";
import TopButton from "@/components/Pengyq/TopButton.vue";
import { uploadFile } from "@/utils/uploadFile"
import { showDialog } from 'vant';
import { debounce } from "@/utils/debounce"
import { itemStore } from "@/stores/item";
import {
  itemDetailImagsUp,
  itemImagsListUp,
  issueItemCommodity,
} from "@/server/api/ItemCommodity";
import { enableRateAPI } from "@/server/api/shopCommodity";
import { getItemIdByUserIdAPI } from "@/server/api/userInfo";

import {
  selectAllAddressAPI,
  insectBuyerDataAPI,
  updateBuyerDataByIdAPI,
  selectAllBrandListAPI,
  topCateListAPI,
  secondCateListAPI,
  setSkulist,
} from "@/server/api/BuyerData";
import { useRoute, useRouter } from "vue-router";

import { itemCommodityDetail, getListSku } from "@/server/api/itemApi"





import { countryList } from "@/data/countryList";
import { ToastFun } from "@/hook/toast";
import { itemFansSum } from "@/server/api/itemApi";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
/**
 * & 注册区
 */
const route = useRoute();
const router = useRouter();
const useUse = useUseStore(); //实例化数据
const useStore = useUseStore(); //导入itemID
const userId = useStore.userId; // 用户Id
/**
 * & 变量声明区
 */
const swiperImg = ref([]); //绑定轮播图地址
const detailImg = ref([]); //绑定商品详情图片
const addersList = ref(null); //自定义地址
const chosenAddressId = ref("1");
const topCateLists = ref(null); //一级分类列表
const topCateList = ref(null); //选中的一级分类
const secondCateLists = ref(null); //二级分类列表
const secondCateList = ref(null); //选中的二级分类
const indexAie = ref(0); // 存储下标
const showAdd = ref(""); //显示选择的地址
const Category = ref(null); //分类显示
const isRate = ref(null); //汇率
const newRegion = ref(null);

const countryData = ref(null); // 国家列表
const selectAllCountryCode = ref(); //所有国家代码
const selectedCountryCodes = ref([]); //选择国家代码数组格式
const isCheckCountryCodeAll = ref(false); //是否全选国家代码

const showPicker = ref(false); //地址弹窗
const showCategory = ref(false); // 一级分类弹窗
const secondCatePupo = ref(false); //二级分类弹窗
const showCountry = ref(false); //国家弹窗
const dialogVisible = ref(false); // 控制弹出框的显示与隐藏
const acceptAddressString = ref(null);
const showAddButton = ref(false);
let addOrEdit; //新增/修改状态 0新增 1修改
let initialReq = ref({});
let initialImages = []
let initialDetailImage = [];
const dto = ref({
  commodityId: null, //商品id
  commodityName: "", //商品名
  freeShippingNum: null, //免费起送
  priceOrder: null, //排序
  countryCode: [], //国家
  degreeLoss: null, //磨损
  acceptAddressList: [], //支持发货的地区集合
  categoryId: null, //分类id
  originAddress: "", //地址
  originPhone: "", //手机
  originName: "", //姓名
  detailImages: [], //详情图片
  imageList: [], //图片轮播图集合
  shopId: "", //网店id
  inventory: null, //库存
  details: "", //详情
  price: null, //价格
  piAddress: "", //pi地址
  piBalance: null, //pi
  originPrice: null, //原价
  specification: "", //规格
});
// 定义接受数据
const from = reactive({
  id: "",
  userName: "",
  phone: "",
  address: "",
  buyerDataId: "",
});



/**
 * & 函数区
 */

// 获取商品详情数据接口
const CommodityDetailFun = async (id) => {
  ToastFun("Loading", { duration: 0 });
  let res = await itemCommodityDetail(id);

  if (res.data.code === 200) {
    initialReq.value = JSON.parse(JSON.stringify(res.data.data));
    dto.value = res.data.data
    console.log(dto.value, "商品详情")
    if (res.data.data.imagsList && res.data.data.imagsList.length > 0) {
      swiperImg.value = res.data.data.imagsList.map(img => ({
        url: img // 将图片地址转化为符合 van-uploader 需要的格式
      }));
      initialImages = res.data.data.imagsList
    }
    dto.value.imageList = res.data.data.imagsListCode
    if (res.data.data.detailImages && res.data.data.detailImages.length > 0) {
      detailImg.value = res.data.data.detailImages.map(img => ({
        url: img // 将图片地址转化为符合 van-uploader 需要的格式
      }));
      initialDetailImage = res.data.data.detailImages

    }
    dto.value.detailImages = res.data.data.detailImagesCode
    showAdd.value = `${res.data.data.originName} || ${res.data.data.originPhone} || ${res.data.data.originAddress}`;
    dto.value.countryCode = res.data.data.countryCode
    acceptAddressString.value = res.data.data.acceptAddressList
    existingSkus.value = res.data.data.sku
    getSKU(res.data.data.categoryId)
    // 回显分类
    // 初始化回显数据
    initSkuData(existingSkus.value);
    const resC = await secondCateListAPI(res.data.data.categoryPid);
    if (Array.isArray(resC.data.data) && resC.data.data.length > 0) {
      const secondCategory = resC.data.data.find(item => item.categoryId === res.data.data.categoryId);
      if (secondCategory) {
        Category.value = secondCategory.content;
      }
    }
    ToastFun("show", { msg: "success" });
  }

}



onMounted(() => {
  if (route.query.commodityId) {
    console.log(route.query.commodityId, "商品id")
    CommodityDetailFun(route.query.commodityId)
  }
  selectAllAddress();
  getItemIdByUserId();
  topCateListFun();
  isRater();
  countryListFilter();
});

//国家列表
const countryListFilter = () => {
  countryData.value = countryList;
  selectAllCountryCode.value = countryData.value.map(
    (item) => item.countryCode
  );
};

//选择国家改变时
const passCountryCode = (value) => {
  const checkedCount = value.length;
  isCheckCountryCodeAll.value =
    checkedCount === selectAllCountryCode.value.length;
  dto.value.acceptAddressList = selectedCountryCodes.value.join(", ");
};

//点击是否全选国家
const checkAllChangeCountryCode = (val) => {
  selectedCountryCodes.value = val ? selectAllCountryCode.value : [];
};

//判断是否开启汇率
const isRater = async () => {
  const res = await enableRateAPI();
  isRate.value = res.data;
};

//定义商品一级分类接口
const topCateListFun = async () => {
  const res = await topCateListAPI(0);
  topCateLists.value = res.data.data;
  console.log(res.data.data, "分类");
};

//定义修改一级分类方法
const topCateChange = (index) => {
  indexAie.value = index;
  topCateList.value = topCateLists.value[index];
  secondCateListFun(topCateList.value.categoryId);
};

//定义商品二级分类接口
const secondCateListFun = async (categoryPid) => {
  const res = await secondCateListAPI(categoryPid);
  secondCateLists.value = res.data.data;
  console.log(secondCateLists.value, "二级")
};

//定义修改二级分类方法
const secondCateChange = (index) => {
  showCategory.value = false;
  secondCatePupo.value = false;
  indexAie.value = index;
  secondCateList.value = secondCateLists.value[index];
  Category.value = secondCateLists.value[index].content;
  dto.value.categoryId = secondCateLists.value[index].categoryId;
  console.log(Category.value + ":" + dto.value.categoryId, "分类");
  getSKU(dto.value.categoryId)
};


const getSKU = async (categoryId) => {
  try {
    ToastFun("Loading", { duration: 0 });
    const { data } = await getListSku(categoryId);
    if (data?.code === 200) {
      skuListData.value = data.data || [];
    } else {
      ToastFun("show", { msg: data?.msg || t("item.details.GetSKUError") });
    }
  } catch (error) {
    console.error("获取SKU出错:", error);
    ToastFun("show", { msg: t("item.details.NetworkAnomaly") });
  } finally {
    ToastFun("close");
  }
};

// 定义获取地址方法
const selectAllAddress = async () => {
  const res = await selectAllAddressAPI(useUse.userId);
  addersList.value = res.data.data.map((item) => ({
    id: item.id.toString(),
    name: item.userName,
    tel: item.phone,
    address: item.address,
    isDefault: item.isDefault === 1,
    buyerDataId: item.buyerDataId,
  }));

};

// 图片超过大小轻提示
const onOversize = () => {
  ToastFun("show", {
    msg: t("me.PersonalPosting.tips4")
  });
};

let itemImagsListFiles = ref([]);
//商品图
const itemImagsListUpFun = async (files) => {
  if (!Array.isArray(files)) {
    files = [files];
    itemImagsListFiles.value.push(...files);
  }
  else {
    itemImagsListFiles.value.push(...files);
  }
};

const deleteImagsLis = (file, detail) => {
  itemImagsListFiles.value = itemImagsListFiles.value.filter(item => item.objectUrl !== file.objectUrl)
  if (file.url) {
    const matchedId = Object.keys(initialImages).find(id => initialImages[id] === file.url);
    const index = dto.value.imageList.findIndex(id => id === matchedId);
    dto.value.imageList.splice(index, 1);
  }
};

let itemTopImagsListFiles = ref([]);
//详情图
const itemTopImagsFun = async (files) => {
  if (!Array.isArray(files)) {
    files = [files];
    itemTopImagsListFiles.value.push(...files);
  }
  else {
    itemTopImagsListFiles.value.push(...files);
  }
};

const deleteDetailImages = (file, detail) => {
  itemTopImagsListFiles.value = itemTopImagsListFiles.value.filter(item => item.objectUrl !== file.objectUrl)
  if (file.url) {
    const matchedId = Object.keys(initialDetailImage).find(id => initialDetailImage[id] === file.url);
    const index = dto.value.detailImages.findIndex(id => id === matchedId);
    dto.value.detailImages.splice(index, 1);
  }
};

const findDeletedImages = () => {
  const deletedImages = [];
  const initialImages = initialReq.value.imagsListCode || [];
  const updatedImages = dto.value.imageList || [];
  initialImages.forEach(imageId => {
    if (!updatedImages.includes(imageId)) {
      deletedImages.push(imageId);
    }
  });
  const initialDetailImages = initialReq.value.detailImagesCode || [];
  const updatedDetailImages = dto.value.detailImages || [];
  initialDetailImages.forEach(imageId => {
    if (!updatedDetailImages.includes(imageId)) {
      deletedImages.push(imageId);
    }
  });
  return deletedImages;
};


//提交
const onSubmit = async (values) => {
  // 处理多张图片
  const uploadPromises = itemImagsListFiles.value.map(async (file) => {
    file.status = 'uploading';
    file.message = '上传中...';
    let formData = new FormData();
    formData.append("multipartFile", file.file);
    ToastFun("Loading", { duration: 500 });

    try {
      // 调用后端接口上传单张图片
      let { data } = await itemImagsListUp(formData);

      // 处理上传失败的情况
      if (data.code === 500) {
        showDialog({
          title: '提示',
          message: `${data.msg}`
        }).then(() => {
          // on close
        });
        file.status = 'failed';
        file.message = '上传失败';
        swiperImg.value = swiperImg.value.filter(item => item !== file);
        return;
      }

      // 处理上传成功的情况
      if (data.code === 200) {
        if (!Array.isArray(dto.value.imageList)) {
          dto.value.imageList = [];
        }

        // 检查图片是否已经存在
        const imageExists = dto.value.imageList.some(image => image === data.data);
        if (!imageExists) {
          file.status = 'success';
          file.message = '上传成功';
          dto.value.imageList.push(data.data);  // 保存上传的图片地址
          console.log(dto.value.imageList, "上传图片");
        } else {
          showDialog({
            title: '提示',
            message: "图片已存在",
          }).then(() => {
            // on close
          });
          file.status = 'failed';
          file.message = '上传失败';
          swiperImg.value = swiperImg.value.filter(item => item !== file);
          return;
        }
      }
    } catch (error) {
      console.error("Error uploading image:", error);
      ToastFun("", { msg: t("me.PersonalPosting.shop.imgTips4") });
      file.status = 'failed';
      file.message = '上传异常';
      swiperImg.value = swiperImg.value.filter(item => item !== file);
    }
  });
  const uploadTopPromises = itemTopImagsListFiles.value.map(async (file) => {
    file.status = 'uploading';
    file.message = '上传中...';
    let formData = new FormData();
    formData.append("multipartFile", file.file);

    ToastFun("Loading", { duration: 500 });

    try {
      let { data } = await itemDetailImagsUp(formData);

      if (data.code === 500) {
        showDialog({
          title: '提示',
          message: `${data.msg}`,
        }).then(() => {
          // on close
        });
        file.status = 'failed';
        file.message = '上传失败';
        detailImg.value = detailImg.value.filter(item => item !== file);
        return;
      }

      if (data.code === 200) {
        if (!Array.isArray(dto.value.detailImages)) {
          dto.value.detailImages = [];
        }

        const imageExists = dto.value.detailImages.some(image => image === data.data);
        if (!imageExists) {
          file.status = 'success';
          file.message = '上传成功';
          dto.value.detailImages.push(data.data);  // 添加成功上传的图片
          console.log(dto.value.detailImages, "详情图片");
        } else {
          showDialog({
            title: '提示',
            message: "图片已存在",
          }).then(() => {
            // on close
          });
          file.status = 'failed';
          file.message = '上传失败';
          detailImg.value = detailImg.value.filter(item => item !== file);
        }
      }
    } catch (error) {
      console.error("上传商品详情图片时出错:", error);
      ToastFun("", { msg: t("me.PersonalPosting.shop.imgTips4") });
      file.status = 'failed';
      file.message = '上传异常';
      detailImg.value = detailImg.value.filter(item => item !== file);
    }
  });
  // 执行所有上传请求
  try {
    await Promise.all(uploadPromises);  // 等待所有上传请求完成
  } catch (error) {
    console.error("批量上传异常:", error);
  }
  try {
    await Promise.all(uploadTopPromises);
  } catch (error) {
    console.error("批量上传异常:", error);
  }

  ToastFun("Loading", {
    duration: 2000 // 2秒后自动关闭
  });

  if (route.query.commodityId) {
    const isAnySpecSelected = Object.values(selectedSpecs.value).some(
      (value) => value && value.length > 0
    );
    if (!isAnySpecSelected) {
      ToastFun("show", { msg: t("item.details.size1") });
      return false;
    }
    const submitData = skuList.value.map((sku) => ({
      price: sku.price,
      orignPrice: sku.orignPrice,
      inventory: sku.inventory,
      piPrice: sku.piPrice,
      degreeLose: sku.degreeLose,
      commoditySpec: sku.selectedSpecs  // 包含选中的规格数据
    }));

    const data = {
      commodityId: route.query.commodityId,
      commodityName: dto.value.commodityName,
      freeShippingNum: dto.value.freeShippingNum, //免费起送
      priceOrder: null, //排序
      countryCode: [], //国家
      degreeLoss: dto.value.degreeLoss, //磨损
      acceptAddressList: dto.value.acceptAddressList, //支持发货的地区集合
      categoryId: dto.value.categoryId, //分类id
      originAddress: dto.value.originAddress, //地址
      originPhone: dto.value.originPhone, //手机
      originName: dto.value.originName, //姓名
      deleteImageList: [],
      detailImages: dto.value.detailImagesCode, //详情图片
      imageList: dto.value.imagsListCode, //图片轮播图集合
      shopId: useStore.itemId,
      inventory: dto.value.inventory, //库存
      details: dto.value.details, //详情
      price: dto.value.price, //价格
      piAddress: dto.value.piAddress, //pi地址
      piBalance: dto.value.piBalance, //pi
      originPrice: dto.value.originPrice, //原价
      specification: dto.value.specification, //规格
      skuList: submitData
    }
    // 处理删除图片
    const deletedImages = findDeletedImages();
    if (deletedImages.length > 0) {
      data.deleteImageList = deletedImages;
    }
    const res = await issueItemCommodity(data);
    console.log(res);
    if (res.data.code === 200) {
      ToastFun("show", { msg: "success" });
      ToastFun("close", {});
      itemStore().itemData = null
      router.back()
    }


  } else {
    dto.value.shopId = useStore.itemId;
    const isAnySpecSelected = Object.values(selectedSpecs.value).some(
      (value) => value && value.length > 0
    );
    if (!isAnySpecSelected) {
      ToastFun("show", { msg: t("item.details.size1") });
      return false;
    }
    const submitData = skuList.value.map((sku) => ({
      price: sku.price,
      orignPrice: sku.orignPrice,
      inventory: sku.inventory,
      piPrice: sku.piPrice,
      degreeLose: sku.degreeLose,
      commoditySpec: sku.selectedSpecs  // 包含选中的规格数据
    }));
    dto.value.skuList = submitData
    console.log(dto.value, "提交数据")
    ToastFun("Loading", { duration: 0 });
    const res = await issueItemCommodity(dto.value);
    if (res.data.code == 200) {
      useUseStore().Upload -= 1;
      setTimeout(() => {
        ToastFun("show", {
          msg: t("pay.success2")
        });
        router.back()
      }, 2000); // 延迟 2000 毫秒（2秒）后显示
    } else {
      ToastFun("", { msg: t("pay.fail2") });
    }

  }

};

const debouncedIssueShopCommodityFun = debounce(onSubmit, 1000);

//选中地址
const selectAddress = (item, index) => {
  showPicker.value = false;
  dto.value.originAddress = item.address;
  dto.value.originPhone = item.tel;
  dto.value.originName = item.name;
  showAdd.value = `${item.name} || ${item.tel} || ${item.address}`;
  console.log(item, index);
};

const onConfirm = ({ selectedOptions }) => {
  // result.value = selectedOptions[0]?.text;
  showPicker.value = false;
};

// 获取用户itemId
const getItemIdByUserId = async () => {
  const res = await getItemIdByUserIdAPI(userId);
  console.log("itemID", res.data.data);
  useUseStore().itemId = res.data.data;
};

// 关闭弹出框
const closeDialog = () => {
  dialogVisible.value = false;
  newRegion.value = ""; // 清空输入框
};
//新建地址
const onAdd = () => {
  showAddButton.value = true;
  addOrEdit = 0;
  from.id = "";
  from.userName = "";
  from.phone = "";
  from.address = "";
};
//编辑地址
const onEdit = (item, index) => {
  addOrEdit = 1;
  from.id = item.id;
  from.userName = item.name;
  from.phone = item.tel;
  from.address = item.address;
  from.buyerDataId = item.buyerDataId;
  console.log(item);
  console.log("item" + item.buyerDataId);
  showAddButton.value = true;
};
//定义修改地址方法
const updateBuyerDataById = async (data) => {
  const res = await updateBuyerDataByIdAPI(data);
  if (res.data.code === 200) {
    selectAllAddress();
    showAddButton.value = false;
  }
};
const insectBuyerData = async (data) => {
  ToastFun("Loading", { duration: 1000 });
  const res = await insectBuyerDataAPI(data);
  console.log(res);
  if (res.data.code === 200) {
    ToastFun("", {});
    selectAllAddress();
    showAddButton.value = false;
    // router.push({
    //   path: `MeView`,
    // });
  }
};
//确认新增/修改
const finish = () => {
  if (addOrEdit === 1) {
    let data = {
      id: from.id,
      address: from.address,
      phone: from.phone,
      buyerDataId: from.buyerDataId,
      userName: from.userName,
    };
    console.log("data修改的内容" + data);

    updateBuyerDataById(data);
  } else {
    let data = {
      address: from.address,
      phone: from.phone,
      userId: useStore.userId,
      userName: from.userName,
    };
    insectBuyerData(data);
  }
};
//添加地区
const addRegion = () => {
  const trimmedRegion = newRegion.value.trim(); // 获取修整后的地区名称

  if (trimmedRegion) {
    // 将新的地区名称添加到 acceptAddressList 中
    dto.value.acceptAddressList.push(trimmedRegion);

    // 拼接新的地区名称到 acceptAddressString
    if (acceptAddressString.value) {
      acceptAddressString.value += `, ${trimmedRegion}`; // 如果已经有内容，添加逗号分隔
    } else {
      acceptAddressString.value = trimmedRegion; // 如果没有内容，直接赋值
    }
    // 清空输入框并关闭对话框
    nextTick(() => {
      newRegion.value = ""; // 清空输入框
      dialogVisible.value = false; // 关闭弹出框
    });
  } else {
    ToastFun("", { msg: t("me.PersonalPosting.shop.addressTips2") });
  }
};


const validate = (field) => {
  if (dto.value[field] < 0) {
    dto.value[field] = 1;
    ToastFun("show", { msg: t("me.PersonalPosting.integer") });
  }
};


// 初始化规格数据 回显
const existingSkus = ref()
// 初始化规格数据
const skuListData = ref({});
// 存储用户选择的规格值
const selectedSpecs = ref({});
for (const specName in skuListData.value) {
  selectedSpecs.value[specName] = []; // 初始化为空数组
}
// SKU 组合
const skuList = ref([]);

// 初始化回显数据
const initSkuData = (existingSkus) => {
  console.log(existingSkus, "回显数据")
  for (const specName in skuListData.value) {
    if (!Array.isArray(selectedSpecs.value[specName])) {
      selectedSpecs.value[specName] = []
    }
  }

  // 根据已有的 SKU 数据回显规格值
  existingSkus.forEach((sku) => {
    for (const [specName, specValue] of Object.entries(sku.commoditySpec)) {
      if (!Array.isArray(selectedSpecs.value[specName])) {
        selectedSpecs.value[specName] = [];
      }
      if (!selectedSpecs.value[specName].includes(specValue)) {
        selectedSpecs.value[specName].push(specValue);
      }
    }
  });


  // 回显 SKU 列表
  skuList.value = existingSkus.map((sku) => ({
    combination: Object.values(sku.commoditySpec).join(" / "),
    price: sku.price,
    orignPrice: sku.orignPrice,
    inventory: sku.inventory,
    piPrice: sku.piPrice,
    degreeLose: sku.degreeLose,
    selectedSpecs: sku.commoditySpec, // 规格组合
  }));
};

// 切换规格值的选中状态
const selectSpecValue = (specName, value) => {
  if (!Array.isArray(selectedSpecs.value[specName])) {
    selectedSpecs.value[specName] = [];
  }
  const specValues = selectedSpecs.value[specName];
  if (specValues.includes(value)) {
    // 如果已选中，则取消选中
    selectedSpecs.value[specName] = specValues.filter((v) => v !== value);
  } else {
    // 如果未选中，则添加
    selectedSpecs.value[specName].push(value);
  }
  generateSku();
};

// 生成 SKU 的详细信息
const generateSku = () => {
  const selectedValues = Object.values(selectedSpecs.value).filter((values) => values.length > 0);
  if (selectedValues.length === 0) {
    skuList.value = [];
    return;
  }

  // 计算笛卡尔积
  const combinations = cartesianProduct(...selectedValues);

  // 生成或更新 SKU 列表
  skuList.value = combinations.map((combination) => {
    const existingSku = skuList.value.find(
      (sku) => sku.combination === combination.join(" / ")
    );
    return {
      combination: Array.isArray(combination) ? combination.join(" / ") : combination,
      price: existingSku?.price || "",
      orignPrice: existingSku?.orignPrice || "",
      inventory: existingSku?.inventory || "",
      piPrice: existingSku?.piPrice || "",
      degreeLose: existingSku?.degreeLose || "",
      selectedSpecs: generateSelectedSpecs(combination),
    };
  });
};

// 生成每个 SKU 组合的规格信息
const generateSelectedSpecs = (combination) => {
  const specNames = Object.keys(selectedSpecs.value);
  const specValues = combination;
  const selectedSpecsObj = {};
  specNames.forEach((specName, index) => {
    selectedSpecsObj[specName] = specValues[index];
  });
  return selectedSpecsObj;
};

// 笛卡尔积计算函数
const cartesianProduct = (...arrays) => {
  if (arrays.length === 0) return [];
  return arrays.reduce((acc, curr) => {
    return acc.flatMap((a) => curr.map((b) => [].concat(a, b)));
  }, [[]]);
};


const validatePrice = (sku, field) => {
  let value = sku[field];

  if (value < 0) {
    ToastFun("show", { msg: t("me.PersonalPosting.integer2") });
    sku[field] = 0;
  }
};


const validateInventory = (sku, field) => {
  let value = sku[field].trim();
  if (value === "") {
    return;
  }
  if (!/^[1-9]\d*$/.test(value)) {
    ToastFun("show", { msg: t("me.PersonalPosting.integer3") });
    sku[field] = 1;
  }
};

const validatePoints = (sku, field) => {
  let value = sku[field];

  if (value === "") {
    return;
  }
  if (/^0\d+/.test(String(value))) {
    ToastFun("show", { msg: t("me.PersonalPosting.integer4") });
    sku[field] = 0;
    return;
  }
  if (isNaN(value)) {
    ToastFun("show", { msg: t("me.PersonalPosting.integer5") });
    sku[field] = 0;
    return;
  }
  value = Number(value);
  if (value < 0) {
    ToastFun("show", { msg: t("me.PersonalPosting.integer2") });
    sku[field] = 0;
  } else {
    sku[field] = value;
  }
};

const validateWear = (sku, field) => {
  let value = sku[field];

  // 如果输入为空，允许清空
  if (value === "") {
    return;
  }

  // 修改正则表达式，允许 0 到 10 之间的整数
  if (!/^(?:[0-9]|10)$/.test(String(value))) {
    ToastFun("show", { msg: t("me.PersonalPosting.integer6") });
    sku[field] = 0; // 设置默认值为 0
    return;
  }
};



</script>
<template>
  <div class="content">
    <TopButton :title="$t('me.PersonalPosting.item.title')" />

    <div class="itemForm">
      <van-form @submit="debouncedIssueShopCommodityFun">
        <!-- 商品图片 -->
        <van-cell-group inset>
          <van-field name="uploader" label="商品图片" :rules="[
            { required: true, message: $t('me.PersonalPosting.item.tips1') },
          ]">
            <template #input>
              <van-uploader preview-size="50rem" :after-read="itemImagsListUpFun" :max-count="5" :max-size="5000 * 1024"
                v-model="swiperImg" @oversize="onOversize" @delete="deleteImagsLis" multiple />
            </template>
          </van-field>

          <!-- 请上传商品详情图片 $t('me.PersonalPosting.item.tips2') -->
          <van-field name="uploader" label="详情图片" :rules="[
            { required: true, message: $t('me.PersonalPosting.item.tips1') },
          ]">
            <template #input>
              <van-uploader preview-size="50rem" :after-read="itemTopImagsFun" :max-count="5" :max-size="5000 * 1024"
                v-model="detailImg" @oversize="onOversize" @delete="deleteDetailImages" multiple />
            </template>
          </van-field>
        </van-cell-group>

        <van-cell-group style="margin-top: 10rem" inset>
          <!-- 产品名称 -->
          <van-field v-model="dto.commodityName" :label="$t('me.PersonalPosting.itemName')" name="asyncValidator"
            :placeholder="$t('me.PersonalPosting.itemNameTips')" :rules="[
              { required: true, message: $t('me.PersonalPosting.rules') },
            ]" />

          <!-- 详情 -->
          <van-field v-model="dto.details" :label="$t('me.PersonalPosting.details')" name="validator"
            :placeholder="$t('me.PersonalPosting.detailsTips')" :rules="[
              { required: true, message: $t('me.PersonalPosting.detailsTips') },
            ]" />

          <!-- 免费 -->
          <van-field v-model.number="dto.freeShippingNum" :label="$t('me.PersonalPosting.free')" name="validator"
            :placeholder="$t('me.PersonalPosting.freeTips')" :rules="[
              { required: true, message: $t('me.PersonalPosting.rules') },
            ]" type="number" @input="validate('freeShippingNum')" />
        </van-cell-group>

        <van-cell-group style="margin-top: 10rem" inset>
          <!-- piAddress -->
          <van-field label="piAddress" v-model="dto.piAddress" :placeholder="'piAddress'" :rules="[
            { required: true, message: $t('me.PersonalPosting.rules') },
          ]" />

          <!-- 发货地 -->
          <van-field :label="$t('me.PersonalPosting.origin')" v-model="showAdd" is-link readonly name="picker"
            placeholder="点击选择城市" @click="showPicker = true" :rules="[
              { required: true, message: $t('me.PersonalPosting.rules') },
            ]" />
          <van-popup v-model:show="showPicker" position="bottom"
            :style="{ height: '60%', backgroundColor: '#F5F5F5FF' }">
            <van-address-list v-model="chosenAddressId" :list="addersList" @select="selectAddress" @add="onAdd"
              @edit="onEdit" />
            <!-- <div class="footer">
              <footer @click="showAddButton=true">
                <div class="icon">+</div>
                {{ $t("me.addAddress") }}
              </footer>
            </div> -->
          </van-popup>
          <!-- 新增/编辑地址弹窗 -->
          <van-popup v-model:show="showAddButton" position="bottom">
            <div style="text-align: center; font-size: 18px; padding-top: 20px">
              {{ addOrEdit ? $t("me.editAddress") : $t("me.addAddress") }}
            </div>
            <div class="addNewAddress">
              <ul>
                <li>
                  <label class="cut-txt">
                    {{ $t("me.addNewAddress.name") }}
                  </label>
                  <input type="text" v-model="from.userName" :rules="[
                    {
                      required: true,
                      message: $t('me.addNewAddress.setName'),
                    },
                  ]" />
                </li>
                <li>
                  <label class="cut-txt">
                    {{ $t("me.addNewAddress.phone") }}
                  </label>
                  <input type="text" v-model="from.phone" />
                </li>
                <li>
                  <label class="cut-txt">
                    {{ $t("me.addNewAddress.address") }}
                  </label>
                  <input type="text" v-model="from.address" />
                </li>
              </ul>
              <footer @click="finish" style="color: white">
                {{ addOrEdit ? $t("me.editAddress") : $t("me.addAddress") }}
              </footer>
            </div>
          </van-popup>
          <!-- 销往哪个国家 -->
          <van-field is-link readonly name="country" :label="$t('ReceivingCountry')"
            :placeholder="$t('ReceivingCountry')" class="text-end" v-model="dto.acceptAddressList"
            @click="showCountry = true" :rules="[{ required: true, message: $t('ReceivingCountry') }]" />

          <!-- 国家弹窗 -->
          <van-popup v-model:show="showCountry" round class="pop" position="bottom"
            :style="{ height: '50%', backgroundColor: '#F5F5F5FF' }">
            <ul class="countrySelect">
              <li>
                <van-checkbox v-model="isCheckCountryCodeAll" @change="checkAllChangeCountryCode">
                  全选
                </van-checkbox>
              </li>
              <van-checkbox-group v-model="selectedCountryCodes" @change="passCountryCode">
                <li v-for="item in countryData" :key="item.countryCode">
                  <van-checkbox :name="item.countryCode" />
                  <div class="country">{{ item.countryEName }}</div>
                  <img :src="`/images/countryImg/${item.img}`" />
                </li>
              </van-checkbox-group>
            </ul>
          </van-popup>

          <!-- 支持发货的地区集合 -->
          <!-- <van-field
            :label="$t('NoFreeShippingAreas')"
            class="text-end"
            v-model="acceptAddressString"
            is-link
            readonly
            name="acceptAddressList"
            :placeholder="$t('NoFreeShippingAreas')"
            @click="dialogVisible = true"
            :rules="[{ required: true, message: $t('NoFreeShippingAreas') }]"
          />

          <van-dialog
            v-model:show="dialogVisible"
            title="输入地区"
            show-confirm-button
            show-cancel-button
            @confirm="addRegion"
            @cancel="closeDialog"
          >
            <van-field v-model="newRegion" placeholder="请输入地区名称" />
          </van-dialog> -->
        </van-cell-group>

        <van-cell-group style="margin-top: 10rem" inset>
          <!-- 分类 -->
          <van-field :label="$t('me.PersonalPosting.item.selectCategory')" v-model="Category" is-link readonly
            name="category" placeholder="分类" @click="showCategory = true" :rules="[
              { required: true, message: $t('me.PersonalPosting.rules') },
            ]" />
          <!-- 一级分类 -->
          <van-popup v-model:show="showCategory" position="bottom"
            :style="{ height: '60%', backgroundColor: '#F5F5F5FF' }">
            <ul class="addersList">
              <li v-for="(item, index) in topCateLists" :key="index" :class="{ border: index == indexAie }"
                @click="topCateChange(index), (secondCatePupo = true)">
                <p class="ellipsis-2">
                  {{ $t(`item.categoryTitle.${item.content}`) }}
                </p>
              </li>
            </ul>
          </van-popup>
          <!-- 二级分类 -->
          <van-popup v-model:show="secondCatePupo" closeable position="bottom"
            :style="{ height: '50%', backgroundColor: '#F5F5F5FF' }">
            <ul class="addersList">
              <div class="first_content">{{ topCateList.content }}</div>
              <li v-for="(item, index) in secondCateLists" :key="index" :class="{ border: index == indexAie }"
                @click="secondCateChange(index)">
                <p class="ellipsis-2">
                  {{ $t(`onlineShop.${item.content}`) }}
                </p>
              </li>
            </ul>
          </van-popup>
          <!-- 
   
          <van-field v-model="dto.specification" label="规格" name="asyncValidator" placeholder="以英文道号符分割 列：S码,L码" :rules="[
            { required: true, message: $t('me.PersonalPosting.rules') },
          ]" />


          <van-field v-model.number="dto.inventory" type="digit" :label="$t('me.PersonalPosting.inventory')"
            name="validator" :placeholder="$t('me.PersonalPosting.inventoryTips')" :rules="[
              { required: true, message: $t('me.PersonalPosting.rules') },
            ]" />


          <van-field v-model.number="dto.price" type="number" label="价格" @input="validate('price')" name="validator"
            placeholder="请输入价格" :rules="[
              { required: true, message: $t('me.PersonalPosting.rules') },
            ]" />


          <van-field v-model.number="dto.originPrice" type="number" @input="validate('originPrice')" label="原价"
            name="validator" placeholder="请输入原价" :rules="[
              { required: true, message: $t('me.PersonalPosting.rules') },
            ]" />


          <van-field v-model.number="dto.piBalance" label="pi积分" type="number" @input="validate('piBalance')"
            name="validator" placeholder="请输入pi" :rules="[
              { required: true, message: $t('me.PersonalPosting.rules') },
            ]" />

          <van-field v-model.number="dto.degreeLoss" @input="validate('degreeLoss')" type="number" label="磨损"
            name="validator" placeholder="请输入磨损" :rules="[
              { required: true, message: $t('me.PersonalPosting.rules') },
            ]" /> -->
        </van-cell-group>




        <van-cell-group inset>
          <!-- 动态渲染规格项 -->
          <div v-for="(specValues, specName) in skuListData" :key="specName" style="margin-bottom: 1rem;">
            <!-- 显示规格名称 -->
            <div style="display: flex; align-items: center; gap: 1rem;">
              <van-field :value="specName" :label="specName" type="text" label-width="auto"
                style="flex: 1; color: #000;" disabled />
            </div>

            <!-- 动态渲染规格值 -->
            <div style="display: flex; gap: 1rem; flex-wrap: wrap;">
              <van-button v-for="(value, valueIndex) in specValues" :key="valueIndex"
                :type="selectedSpecs[specName]?.includes(value) ? 'primary' : 'default'"
                @click="selectSpecValue(specName, value)" size="small">
                {{ value }}
              </van-button>
            </div>
          </div>

          <!-- 显示 SKU 组合 -->
          <div v-for="(sku, index) in skuList" :key="index"
            style="margin-top: 1rem; padding: 1rem; border: 1px solid #ccc;">
            <div>{{ sku.combination }}</div>

            <!-- 添加 SKU 的详细信息 -->
            <div style="display: flex; flex-direction: column; gap: 1rem; margin-top: 0.5rem;">
              <div style="display: flex; gap: 1rem;">
                <van-field v-model.number="sku.price" label="价格" placeholder="输入价格" type="number" style="flex: 1;"
                  label-width="auto" @input="validatePrice(sku, 'price')" :rules="[
                    { required: true, message: $t('me.PersonalPosting.rules') },
                  ]" />
                <van-field v-model.number="sku.orignPrice" label="原价" placeholder="输入原价" type="number" style="flex: 1;"
                  label-width="auto" @input="validatePrice(sku, 'orignPrice')" :rules="[
                    { required: true, message: $t('me.PersonalPosting.rules') },
                  ]" />
              </div>
              <div style="display: flex; gap: 1rem;">
                <van-field v-model="sku.inventory" label="库存" placeholder="输入库存" type="digit" style="flex: 1;"
                  label-width="auto" @input="validateInventory(sku, 'inventory')" :rules="[
                    { required: true, message: $t('me.PersonalPosting.rules') },
                  ]" />
                <van-field v-model.number="sku.piPrice" label="积分" placeholder="输入积分" type="number" style="flex: 1;"
                  label-width="auto" @input="validatePoints(sku, 'piPrice')" :rules="[
                    { required: true, message: $t('me.PersonalPosting.rules') },
                  ]" />
              </div>
              <div style="display: flex; gap: 1rem;">
                <van-field v-model="sku.degreeLose" label="磨损" placeholder="输入磨损度0-10" type="digit" style="flex: 1;"
                  label-width="auto" @input="validateWear(sku, 'degreeLose')" :rules="[
                    { required: true, message: $t('me.PersonalPosting.rules') },
                  ]" />
              </div>
            </div>
          </div>

        </van-cell-group>




        <div style="margin: 16px">
          <van-button round block type="primary" native-type="submit">
            提交
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.content {
  .itemForm {
    font-size: 14rem;
    background-color: #f5f5f5;
    padding: 70rem 0 0 0;

    .van-popup--bottom {

      .addersList {
        :deep(.van-field__label) {
          width: auto;
        }

        padding-top: 40rem;

        .first_content {
          font-size: 20rem;
          margin-left: 20rem;
          margin-bottom: 20rem;
          font-weight: 600;
        }

        li {
          border: 1rem solid transparent;
          box-sizing: border-box;
          width: 90%;
          margin: 10rem auto;
          background-color: #ffffff;
          border-radius: 10rem;
          padding: 10rem 15rem;

          p {
            width: 70%;
            font-size: 16rem;
            line-height: 30rem;
          }

          .footer_en {
            display: flex;
            justify-content: space-between;

            .info {
              color: #ccc;
              display: flex;
              font-size: 16rem;
              line-height: 30rem;

              .name {
                margin-right: 10rem;
              }
            }

            .text_right {
              width: 58rem;
              height: 36rem;
              text-align: center;
              line-height: 36rem;
              white-space: nowrap;
              color: #642e8eff;
              border: 1rem solid;
              border-radius: 5rem;
            }
          }

          &.border {
            border: 1rem solid #642e8eff;
          }
        }

        .ellipsis-3 {
          line-height: 50rem;
          font-size: 16rem;
          font-weight: 500;
          margin-left: 20rem;
          padding-left: 15rem;
          background-color: #fff;
          width: 348rem;
          height: 50rem;
          border-radius: 10rem;
          margin-bottom: 10rem;
          // &:hover{
          //   border: 2rem solid #642e8eff;
          // }
        }
      }

      footer {
        position: relative;
        bottom: 0rem;
        left: 10rem;
        width: 90%;
        height: 50rem;
        display: flex;
        justify-content: center;
        color: #642e8eff;
        border: 2rem solid;
        border-radius: 10rem;
        font-size: 18rem;
        align-items: center;

        .icon {
          margin-right: 10rem;
          width: 25rem;
          height: 25rem;
          text-align: center;
          line-height: 25rem;
          border: 2rem solid;
          color: #642e8eff;
          border-radius: 50%;
          font-size: 20rem;
        }
      }
    }

    .pop {
      .countrySelect {
        width: 390rem;
        height: 500rem;

        li {
          padding: 10rem;
          display: flex;
          bottom: 1px solid;
          justify-content: space-between;

          .country {
            font-size: 16rem;
            font-weight: bold;
          }

          img {
            width: 30rem;
            height: 30rem;
          }
        }
      }

      .regionSelect {
        width: 390rem;
        height: 500rem;

        li {
          padding: 10rem;
          display: flex;
          bottom: 1px solid;
          justify-content: space-between;

          .region {
            font-size: 16rem;
            font-weight: bold;
          }
        }
      }
    }
  }
}

.addNewAddress {
  font-size: 14rem;
  padding: 60rem 10rem 0;
  // color: black;

  ul {
    padding: 10rem;

    li {
      position: relative;
      margin-bottom: 20rem;
      display: flex;
      justify-content: space-between;

      label {
        line-height: 40rem;
        width: 70rem;
      }

      input {
        flex: 1;
        padding-left: 15rem;
        border: 0;
        background-color: #f5f5f5;
        border-radius: 10rem;
        height: 40rem;
      }

      .icon {
        top: 10rem;
        right: 10rem;
        position: absolute;
      }
    }
  }

  footer {
    position: absolute;
    bottom: 30rem;
    border-radius: 10rem;
    text-align: center;
    line-height: 40rem;
    color: #080808;
    font-size: 16rem;
    width: 90%;
    margin: 0 auto;
    height: 40rem;
    background-color: #642e8e;
  }
}
</style>
